// pages/order/orderList/orderList.js
import getIn from '../../../sdk/utils/getIn';
import { ORDER_TYPE_AUDITE, ORDER_TYPE_UNPAID, ORDER_TYPE_PAID, ORDER_TYPE_COMPLETED, ORDER_TYPE_CANCELED, ORDER_TYPE_CLOSED } from '../../../utils/config'
import {ORDER_DETAIL, PRICE_DETAIL} from "../../../utils/url";
import {API_ORDER_CHANGE_STATUS, API_MY_ORDER_LIST, API_ORDER_LIST, API_ORDER_DETAIL} from "../../../sdk/business/url";
import { addNotifier, removeNotifier, notify } from "../../../sdk/utils/NotifyRegistryCenter.js";
import {showFail, showSuccess} from "../../../utils/util";
import { wxPay } from '../../../utils/orderPay'
Page({

  /**
   * 页面的初始数据
   */
  data: {
      menuItems: [
          { name: '全部', status: -1 },
          { name: '待审核', status: ORDER_TYPE_AUDITE },
          { name: '待支付', status: ORDER_TYPE_UNPAID },
          { name: '已付款', status: ORDER_TYPE_PAID },
          { name: '已完成', status: ORDER_TYPE_COMPLETED },
          { name: '已取消', status: ORDER_TYPE_CANCELED },
          { name: '已关闭', status: ORDER_TYPE_CLOSED }
      ],
      ORDER_TYPE_AUDITE,
      ORDER_TYPE_UNPAID,
      ORDER_TYPE_PAID,
      ORDER_TYPE_COMPLETED,
      ORDER_TYPE_CANCELED,
      ORDER_TYPE_CLOSED,
      currentIndex: 0,
      params: {
          page: 1,
          rows: 5,
      },
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
      setTimeout(() => { this.setData({ refresh: true }) }, 800);
      setTimeout(() => { this.setData({ refresh: false }) }, 8000);
      const status = options.status != undefined ? Number(options.status) : this.data.params.status;
      const currentIndex = this.data.menuItems.findIndex(x => x.status == status);
      const userInfo = getApp().globalData.userInfo;
      this.setData({ currentIndex: currentIndex > -1 ? currentIndex: 0, userInfo }, () => {
          this.onRefresh()
      });
      addNotifier && addNotifier('updateorderlist', this.onPullDownRefresh, this)
  },
    onRefresh() {
        // if (this.data.loading) return;
        const token = getIn(getApp(), ['globalData', 'token']);
        const status = this.data.menuItems[this.data.currentIndex].status;
        const params = this.data.currentIndex == 0 ? { ...this.data.params, token } : { token, ...this.data.params, status };
        wx.showLoading();
        this.setData({ loading: true });
        // member_type_nature为0时，获取用户列表
        const apiLink = this.data.userInfo.member_type_nature ? API_ORDER_LIST : API_MY_ORDER_LIST
        global.request(apiLink, params, (code, res) => {
            if (code == 'SUCCESS') {
                const total = getIn(res.data, ['total']);
                let orderList = getIn(res.data, ['list']);
                orderList = orderList && orderList.map((x) => {
                    x.statusText = this.statusText(x.status);
                    return x
                })
                orderList = params.page == 1 ? orderList : this.data.orderList.concat(orderList);
                this.setData({ orderList, total, listFooterTitle: orderList.length < total ? '加载更多' : '已加载完成', loading: false });
                wx.stopPullDownRefresh();
                wx.hideLoading();
            } else if (status == 'FAIL') {
                wx.stopPullDownRefresh();
                wx.hideLoading()
                this.setData({ loading: false })
            }
        })
    },
    // 状态名称
    statusText(type) {
        let text = '';
        switch(type) {
            case ORDER_TYPE_AUDITE: {
                text = '待审核';
                break;
            }
            case ORDER_TYPE_UNPAID: {
                text = '待支付';
                break;
            }
            case ORDER_TYPE_PAID: {
                text = '已付款';
                break;
            }
            case ORDER_TYPE_COMPLETED: {
                text = '已完成';
                break;
            }
            case ORDER_TYPE_CANCELED: {
                text = '已取消';
                break;
            }
            case ORDER_TYPE_CLOSED: {
                text = '已关闭';
                break;
            }
        }
        return text;
    },
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh () {
        const page = 1;
        const params = {...this.data.params, page}
        this.data.params = params;
        this.onRefresh();
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom () {
        const { total, orderList } = this.data;
        if (orderList.length < total) {
            // 界面加载完, 且还有下一页的情况。
            const pages = getIn(this.data, ['params', 'page']) || 1;
            const params = { ...this.data.params, page: pages + 1 };
            this.data.params = params;
            this.onRefresh();
        }
    },
    // 点击订单状态回调
    menuCallBackAction(e) {
        const index = getIn(e, ['detail']);
        this.setData({
            currentIndex: index,
        }, () => {
            this.onPullDownRefresh();
        });
    },
    toOrderDetail(e) {
        const id = getIn(e.currentTarget, ['id']);
        const queryString = `order_id=${id}`;
        global.navigateHelper.navigateTo({ pathname: ORDER_DETAIL, queryString });
    },
    // 拨打电话
    makePhone(e) {
      const phone = getIn(e.currentTarget.dataset, ['phone']);
      wx.makePhoneCall({
        phoneNumber: phone
      })
    },
    // 付款
    pay(e) {
        const token = getIn(getApp(), ['globalData', 'token']);
        const order_id = getIn(e.currentTarget.dataset, ['order_id']);
        const pay_way = 2;
        const trade_type = 'JSAPI';
        const payParams = {
            token, order_id, pay_way, trade_type,
        };
        wxPay(payParams, (status, result) => {
            if (status == 'SUCCESS') {
                // 通知刷新订单列表
                showSuccess('支付成功');
                this.onPullDownRefresh();
            } else if (status == 'PAY_FAIL') {
                showFail('支付失败');
            } else if (status == 'FAIL') {
                showFail(result && result.msg);
            }
        });
    },
    // 取消订单
    cancel(e) {
        const token = getIn(getApp(), ['globalData', 'token']);
        const id = getIn(e.currentTarget.dataset, ['order_id']);
        wx.showModal({
            title: '确定取消订单？',
            success:(res) => {
                if (res.confirm) {
                    global.request(API_ORDER_CHANGE_STATUS, { token, status: ORDER_TYPE_CANCELED, id }, (code, res) => {
                        if (code == 'SUCCESS') {
                            showSuccess('取消成功');
                            this.onPullDownRefresh();
                        } else if (code == 'FAIL') {
                            showFail(res.msg);
                        }
                    });
                }
            }
        })
    },
    // 商家确认接单
    confirm(e) {
        const token = getIn(getApp(), ['globalData', 'token']);
        const id = getIn(e.currentTarget.dataset, ['order_id']);
        wx.showModal({
            title: '系统提示',
            content: '确认接单后，价格将不能修改，确认继续此操作？',
            success:(res) => {
                if (res.confirm) {
                    global.request(API_ORDER_CHANGE_STATUS, { token, status: ORDER_TYPE_UNPAID, id }, (code, res) => {
                        if (code == 'SUCCESS') {
                            showSuccess('操作成功');
                            this.onPullDownRefresh();
                        } else if (code == 'FAIL') {
                            showFail(res.msg);
                        }
                    });
                }
            }
        })
    },
    // 商家完成订单
    complete(e) {
        const token = getIn(getApp(), ['globalData', 'token']);
        const id = getIn(e.currentTarget.dataset, ['order_id']);
        global.request(API_ORDER_CHANGE_STATUS, { token, status: ORDER_TYPE_COMPLETED, id }, (code, res) => {
            if (code == 'SUCCESS') {
                showSuccess('操作成功');
                this.onPullDownRefresh();
            } else if (code == 'FAIL') {
                showFail(res.msg);
            }
        });
    },
    // 商家修改订单
    modifyPrice(e) {
        const token = getIn(getApp(), ['globalData', 'token']);
        const id = getIn(e.currentTarget.dataset, ['order_id']);
        global.request(API_ORDER_DETAIL, { token, id }, (code, res) => {
            if (code == 'SUCCESS') {
                const object = getIn(res, ['data']);
                const queryString = `link_products=${JSON.stringify(object.link_products)}&paid_price=${object.paid_price}&floor_price=${object.floor_price}&id=${id}`;
                global.navigateHelper.navigateTo({ pathname: PRICE_DETAIL, queryString });
            } else if (code == 'FAIL') {
                showFail(res.msg);
            }
        });

    },
    // 退款
    refund(e) {
        const token = getIn(getApp(), ['globalData', 'token']);
        const id = getIn(e.currentTarget.dataset, ['order_id']);
        wx.showModal({
            title: '退款提示',
            content: '你同意后，退款申请即将生效，安逸将会按照微信退款协议，退款给买家',
            success:(res) => {
                if (res.confirm) {
                    global.request(API_ORDER_CHANGE_STATUS, { token, id, status: ORDER_TYPE_CLOSED }, (code, res) => {
                        if (code == 'SUCCESS') {
                            showSuccess('操作成功');
                            this.onPullDownRefresh();
                        } else if (code == 'FAIL') {
                            showFail(res.msg);
                        }
                    })
                }
            }
        })

    },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload () {
      removeNotifier && removeNotifier('updateorderlist', this.onPullDownRefresh, this)
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage () {
  
  }
})